package com.jxd.ordering.controller;

import com.jxd.ordering.annotation.CheckPermission;
import com.jxd.ordering.exception.CommonEnum;
import com.jxd.ordering.exception.serviceexception.*;
import com.jxd.ordering.model.ResultBody;
import com.jxd.ordering.model.User;
import com.jxd.ordering.service.IUserService;
import com.jxd.ordering.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Ankailong
 * @Date 2022/9/28
 * @Version 1.0
 */
@RestController
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 新增用户信息
     * level: 3
     * @param user 用户实体类
     * @return 是否新增成功
     */
    @CheckPermission("3")
    @RequestMapping("/addUser")
    public ResultBody addUser(@RequestBody User user, HttpServletRequest request) throws AccountExistException, PermissionNotAllowedException {
        //如果用户权限等级为3，不可以添加权限等级大于2的用户
        String permission = (String) request.getAttribute("permission");
        if (user.getPermission() > 2 && "3".equals(permission)) {
            throw new PermissionNotAllowedException();
        }
        return userService.addUser(user) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 修改用户信息
     * level: 3
     * @param user 用户实体类
     * @return 是否修改成功
     */
    @RequestMapping("/editUser")
    public ResultBody editUser(@RequestBody User user, HttpServletRequest request) throws PermissionNotAllowedException {
        //临时授权
        if (user.getUserid() != Integer.parseInt(request.getAttribute("userid").toString())) {
            //如果用户权限等级为3，不可以修改除自己之外权限等级大于2的用户
            if (user.getPermission() > 2 && "3".equals(request.getAttribute("permission"))) {
                throw new PermissionNotAllowedException();
            }
            PermissionUtil.PermissionControl(request.getAttribute("permission"), 3);
        }
        return userService.editUser(user) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 修改密码
     * level: 3
     * @param map 包含 userid 用户id  pwd 新密码
     * @return 是否修改成功
     */
    @RequestMapping("/editPassword")
    public ResultBody editPassword(@RequestBody Map<String, String> map, HttpServletRequest request) throws PermissionNotAllowedException {
        int userid = Integer.parseInt(map.get("userid"));
        String pwd = map.get("pwd");
        int permission = Integer.parseInt(userService.getPermissionByUserid(userid));

        //临时授权
        if (userid != Integer.parseInt(request.getAttribute("userid").toString())) {
            //如果用户权限等级为3，不可以修改等级大于2的用户的密码
            if (permission > 2 && "3".equals(request.getAttribute("permission"))) {
                throw new PermissionNotAllowedException();
            }
            PermissionUtil.PermissionControl(request.getAttribute("permission"), 3);
        }
        return userService.editPassword(userid, pwd) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 批量删除用户信息
     * level: 3
     * @param userids 用户编号列表
     * @return 是否删除成功
     */
    @CheckPermission("3")
    @RequestMapping("/delUser")
    public ResultBody delUser(@RequestBody List<Integer> userids, HttpServletRequest request) throws PermissionNotAllowedException {
        for (Integer userid : userids) {
            int permission = Integer.parseInt(userService.getPermissionByUserid(userid));

            //如果用户权限等级为3，不可以删除权限等级大于2的用户
            if (permission > 2 && "3".equals(request.getAttribute("permission"))) {
                throw new PermissionNotAllowedException();
            }
        }

        return userService.delUser(userids.stream().mapToInt(Integer::intValue).toArray()) ? ResultBody.success() : ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 分页查询全部用户信息
     * level: 3
     * @param queryMap 包含 int page, int limit, String uname, int type（1用户 2管理员）
     * @return 查询结果
     */
    @CheckPermission("3")
    @RequestMapping("/getUserByPage")
    public Map<String, Object> getUserByPage(@RequestBody Map<String,String> queryMap, HttpServletRequest request) throws PermissionNotAllowedException {
        //如果用户权限等级为3，不可以等查询管理员信息
        if (!"1".equals(queryMap.get("type")) && "3".equals(request.getAttribute("permission"))) {
            throw new PermissionNotAllowedException();
        }

        return userService.getUserByPage(queryMap);
    }

    /**
     * 按用户编号查询用户信息
     * level: 3
     * @param userid 用户编号
     * @return 查询结果
     */
    @RequestMapping("/getUserByUserid")
    public Map<String, Object> getUserByUserid(int userid, HttpServletRequest request) throws PermissionNotAllowedException {
        int permission = Integer.parseInt(userService.getPermissionByUserid(userid));

        //临时授权
        if (userid != Integer.parseInt(request.getAttribute("userid").toString())) {
            //如果用户权限等级为3，不可以查询除自身之外权限等级大于2的用户
            if (permission > 2 && "3".equals(request.getAttribute("permission"))) {
                throw new PermissionNotAllowedException();
            }
            PermissionUtil.PermissionControl(request.getAttribute("permission"), 3);
        }
        return userService.getUserByUserid(userid);
    }

    /**
     * 登录
     * @param map 包含 account 用户名  pwd 密码
     * @return 用户信息 包含 uname, permission, headshot, userno, token
     */
    @RequestMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> map) throws UserNotFoundException, PwdErrorException {
        return userService.login(map.get("account"), map.get("pwd"));
    }

    /**
     * 注册（管理员手动给员工注册）
     * 权限等级3
     * @param map 包含 account,pwd,uname,sex,tel,deptno,job
     * @return 用户信息 包含 account,pwd
     */
    @CheckPermission("3")
    @RequestMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> map) throws AccountExistException {
        return userService.register(map);
    }
}
